<template>
	<div class="detail" v-if="!loading">
		<Header></Header>
		<div class="tags">
			<van-tag v-for="(item, index) in info.tag_ids || []" :key="index" plain color="#6881ec" style="margin: 0 10px 10px 0;" size="medium">{{ item }}</van-tag>
			<div>
				<van-button style="margin-right: 10px;" size="small" color="#6881ec" @click="handleAdd">添 加</van-button>
				<van-button size="small" color="#6881ec" @click="handleRemove">移 除</van-button>
			</div>
		</div>
		<van-divider style="margin: 0;" />
		<div class="tabs">
			<van-tabs v-model="active" color="#6881ec">
				<van-tab :name="1" title="跟进记录">
					<keep-alive><Follow :info="info" v-if="active === 1"></Follow></keep-alive>
				</van-tab>
				<van-tab :name="2" title="用户画像">
					<keep-alive><Portrait :detail="info" v-if="active === 2"></Portrait></keep-alive>
				</van-tab>
				<van-tab :name="3" title="互动轨迹">
					<keep-alive><Interact v-if="active === 3"></Interact></keep-alive>
				</van-tab>
			</van-tabs>
		</div>
	</div>
</template>

<script>
import { Button, Tag, Divider, Tab, Tabs, Toast } from 'vant';
import Header from './components/Header.vue';
import Follow from './components/Follow.vue';
import Portrait from './components/Portrait.vue';
import Interact from './components/Interact.vue';
import { getCustomerInfo } from '../../api/detail.js';
import { getJsSdk, getUserInfo } from '../../api/index.js';
export default {
	components: {
		Header,
		Follow,
		Portrait,
		Interact,
		[Button.name]: Button,
		[Tag.name]: Tag,
		[Divider.name]: Divider,
		[Tab.name]: Tab,
		[Tabs.name]: Tabs,
		[Toast.name]: Toast
	},
	data() {
		return {
			active: 0,
			info: {},
			loading: true
		};
	},
	created() {
		Toast.loading({
			message: '加载中...',
			forbidClick: true,
			duration: 0
		});
		document.title = '客户详情';
		if (localStorage.getItem('login_user_info')) {
			this.getExternalUserId();
		} else if (this.$getQuery('code')) {
			this.getLoginUserInfo();
		} else {
			this.getCode();
		}
	},
	methods: {
		// 登录获取用户信息
		async getLoginUserInfo() {
			const { code, data } = await getUserInfo({
				code: this.$getQuery('code'),
				corp_id: localStorage.getItem('huankemao_corp_id')
			});
			if (code === 200) {
				localStorage.setItem('login_user_info', JSON.stringify(data));
				localStorage.setItem('huankemao_user_id', data.user_id);
				this.getExternalUserId();
			} else {
				localStorage.removeItem('login_user_info');
				localStorage.removeItem('huankemao_user_id');
				this.getCode();
			}
		},
		// 获取code
		getCode() {
			var url = encodeURI(location.origin + '/chat-tool/detail.html');
			var href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${localStorage.getItem(
				'huankemao_corp_id'
			)}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=detail#wechat_redirect`;
			window.location.href = href;
		},
		// 获取外部联系人userId
		async getExternalUserId() {
			const { res, data, msg } = await getJsSdk({
				url: location.href.split('#')[0]
			});
			wx.config({
				beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
				debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				appId: data.config.appId, // 必填，企业微信的corpID
				timestamp: data.config.timestamp, // 必填，生成签名的时间戳
				nonceStr: data.config.nonceStr, // 必填，生成签名的随机串
				signature: data.config.signature, // 必填，签名，见 附录-JS-SDK使用权限签名算法
				jsApiList: ['getCurExternalContact'] // 必填，需要使用的JS接口列表，凡是要调用的接口都需要传进来
			});
			wx.ready(() => {
				wx.agentConfig({
					corpid: data.agent.corpid, // 必填，企业微信的corpid，必须与当前登录的企业一致
					agentid: data.agent.agentid, // 必填，企业微信的应用id （e.g. 1000247）
					timestamp: data.agent.timestamp, // 必填，生成签名的时间戳
					nonceStr: data.agent.nonceStr, // 必填，生成签名的随机串
					signature: data.agent.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
					jsApiList: ['getCurExternalContact'], //必填，传入需要使用的接口名称
					success: () => {
						wx.invoke('getCurExternalContact', {}, res => {
							if (res.err_msg == 'getCurExternalContact:ok') {
								sessionStorage.setItem('external_user_id', res.userId);
								this.getInfo();
							} else {
								//错误处理
							}
						});
					},
					fail: res => {
						if (res.errMsg.indexOf('function not exist') > -1) {
							alert('版本过低请升级');
						}
					}
				});
			});
			wx.error(res => {
				Toast.fail(res);
			});
		},
		// 获取当前客户详情
		async getInfo() {
			const { code, data, msg } = await getCustomerInfo({
				external_user_id: sessionStorage.getItem('external_user_id'),
				follow_userid: localStorage.getItem('huankemao_user_id'),
				is_api: 1
			});
			if (code === 200) {
				Toast.clear();
				this.info = data;
				sessionStorage.setItem('external_info', JSON.stringify(data));
				this.active = 1;
				this.loading = false;
			} else {
				Toast.fail(msg);
			}
		},
		handleAdd() {
			this.$router.push({
				path: '/detail_label',
				query: {
					id: this.info.id,
					type: 1,
					tags: this.info.tag_ids
				}
			});
		},
		handleRemove() {
			this.$router.push({
				path: '/detail_label',
				query: {
					id: this.info.id,
					type: 2,
					tags: this.info.tag_ids
				}
			});
		}
	}
};
</script>

<style lang="less" scoped>
.detail {
	padding-bottom: 50px;
	.tags {
		padding: 15px 15px 10px;
	}
}
</style>
